package com.nb.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.paginate.Page;
import com.nb.dto.LogStatisticsDTO;
import com.nb.dto.SysLogQueryDTO;
import com.nb.entity.SysLog;
import com.nb.mapper.SysLogMapper;
import com.nb.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class SysLogServiceImpl implements SysLogService {

    @Autowired
    private SysLogMapper sysLogMapper;

    @Override
    public Page<SysLog> getSysLogPage(SysLogQueryDTO queryDTO) {
        // 构建查询条件
        QueryWrapper queryWrapper = QueryWrapper.create();

        // 操作用户ID
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(SysLog::getUserId, queryDTO.getUserId());
        }

        // 操作类型
        if (queryDTO.getAction() != null && !queryDTO.getAction().isEmpty()) {
            queryWrapper.eq(SysLog::getAction, queryDTO.getAction());
        }

        // 操作对象类型
        if (queryDTO.getTargetType() != null && !queryDTO.getTargetType().isEmpty()) {
            queryWrapper.eq(SysLog::getTargetType, queryDTO.getTargetType());
        }

        // 操作对象ID
        if (queryDTO.getTargetId() != null) {
            queryWrapper.eq(SysLog::getTargetId, queryDTO.getTargetId());
        }

        // 操作时间范围 - 开始时间
        if (queryDTO.getStartTime() != null) {
            queryWrapper.ge(SysLog::getCreatedTime, queryDTO.getStartTime());
        }

        // 操作时间范围 - 结束时间
        if (queryDTO.getEndTime() != null) {
            queryWrapper.le(SysLog::getCreatedTime, queryDTO.getEndTime());
        }

        // 按操作时间降序排序
        queryWrapper.orderBy(SysLog::getCreatedTime, false);

        // 执行分页查询
        Page<SysLog> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        return sysLogMapper.paginate(page, queryWrapper);
    }
    @Override
    public SysLog getLogById(Long id) {
        if (id == null) {
            return null;
        }

        QueryWrapper queryWrapper = QueryWrapper.create()
                .where("id = ?", id); // 正确语法：条件表达式 + 参数值

        return sysLogMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<SysLog> queryLogsForCsvExport(
            Long userId,
            String action,
            LocalDateTime startTime,
            LocalDateTime endTime) {

        QueryWrapper queryWrapper = QueryWrapper.create();
        if (userId != null) {
            queryWrapper.eq(SysLog::getUserId, userId);
        }
        if (action != null && !action.isEmpty()) {
            queryWrapper.eq(SysLog::getAction, action);
        }
        if (startTime != null) {
            queryWrapper.ge(SysLog::getCreatedTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(SysLog::getCreatedTime, endTime);
        }
        queryWrapper.orderBy(SysLog::getCreatedTime, false);
        return sysLogMapper.selectListByQuery(queryWrapper);
    }

    @Override
    public List<LogStatisticsDTO.DateCountVO> countByDate(LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select("DATE_FORMAT(created_time, '%Y-%m-%d') as date, COUNT(*) as count")
                .from(SysLog.class)
                .groupBy("DATE_FORMAT(created_time, '%Y-%m-%d')")
                .orderBy("date");

        addTimeRangeCondition(queryWrapper, startTime, endTime);

        return sysLogMapper.selectListByQueryAs(queryWrapper, LogStatisticsDTO.DateCountVO.class);
    }

    @Override
    public List<LogStatisticsDTO.TypeCountVO> countByAction(LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select("action, COUNT(*) as count")
                .from(SysLog.class)
                .groupBy("action")
                .orderBy("count DESC");

        addTimeRangeCondition(queryWrapper, startTime, endTime);

        return sysLogMapper.selectListByQueryAs(queryWrapper, LogStatisticsDTO.TypeCountVO.class);
    }

    @Override
    public List<LogStatisticsDTO.UserCountVO> countByUser(LocalDateTime startTime, LocalDateTime endTime) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select("user_id, COUNT(*) as count")
                .from(SysLog.class)
                .groupBy("user_id")
                .orderBy("count DESC");

        addTimeRangeCondition(queryWrapper, startTime, endTime);

        return sysLogMapper.selectListByQueryAs(queryWrapper, LogStatisticsDTO.UserCountVO.class);
    }

    // 抽取时间范围条件设置为私有方法
    private void addTimeRangeCondition(QueryWrapper queryWrapper, LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime != null) {
            queryWrapper.ge(SysLog::getCreatedTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(SysLog::getCreatedTime, endTime);
        }
    }
}